package com.example.auth.config;

import com.example.auth.interceptor.AuthInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(WebConfig.class);

    @Autowired
    private AuthInterceptor authInterceptor;

    @Value("${app.upload.dir:uploads}")
    private String uploadDir;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        logger.info("Configuring interceptor to verify user permissions"); // Configuring interceptor to verify user permissions
        registry.addInterceptor(authInterceptor)
                .addPathPatterns("/api/**")
                .excludePathPatterns("/api/auth/login", "/api/auth/register");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        logger.info("Configuring CORS to allow frontend access"); // Configuring CORS to allow frontend access
        registry.addMapping("/**")
                .allowedOriginPatterns("*")  // Allow all origins, simplifying development
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);  // Validity period of the preflight request, in seconds

        logger.info("CORS configuration completed, allowing access from all origins"); // CORS configuration completed, allowing access from all origins
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // Get the absolute path of the upload directory
        String uploadPath = new File(uploadDir).getAbsolutePath();

        // Configure static resource mapping, mapping /uploads/** to the actual file directory
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations("file:" + uploadPath + "/");

        logger.info("Configuring resource mapping: /uploads/** -> file:{}/", uploadPath); // Configuring resource mapping: /uploads/** -> file:{}/
    }
}